package com.zou.music_downloader;

import android.app.Dialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.zou.music_downloader.bean.DataBean;
import com.zou.music_downloader.bean.SongsBean;
import com.zou.music_downloader.sqlite.MyDao;
import com.zou.music_downloader.utils.BMA;
import com.zou.music_downloader.utils.FileDownloader;
import com.zou.music_downloader.utils.VolleyUtil;

import java.util.List;

/**
 * 弹出的下载歌曲的DialogFragment
 * Created by zou on 2016/3/13.
 */
public class DownloadDialogFragment extends AppCompatDialogFragment {

    private SongsBean                               bean;
    private List<SongsBean.SongurlEntity.UrlEntity> urls;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        final MyDao    myDao     = new MyDao(getContext());
        final String   songId    = getArguments().getString("id");
        LayoutInflater mInflater = LayoutInflater.from(getActivity());
        View           view      = mInflater.inflate(R.layout.download_dialog, null);


        final TextView songname = (TextView) view.findViewById(R.id.song_name);

        final ImageView  imageView  = (ImageView) view.findViewById(R.id.image_song_album);
        final RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.rg);
        final TextView   tv_down    = (TextView) view.findViewById(R.id.downloaded);
//        判断已下载
        final DataBean dataBean = myDao.alterDateBySongId(songId);
        if (dataBean != null) {
            tv_down.setVisibility(View.VISIBLE);
            tv_down.setText(dataBean.getSongName() + dataBean.getState() + ",再次下载将先删除旧文件");
        }

        final Gson gson = new Gson();

        RequestQueue requestQueue = VolleyUtil.getQueue(getContext());
        StringRequest stringRequest = new StringRequest(BMA.Song.songInfo(songId)
                , new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                bean = gson.fromJson(response, SongsBean.class);
                songname.setText(bean.getSonginfo().getTitle() + " - " + bean.getSonginfo().getAuthor());
                urls = bean.getSongurl().getUrl();


                if (!TextUtils.isEmpty(bean.getSonginfo().getAlbum_500_500())) {
                    Picasso.with(getContext())
                            .load(bean.getSonginfo().getAlbum_500_500())
                            .resize(500, 500)
                            .centerCrop()
                            .error(R.mipmap.ic_error_outline_black_48dp)
                            .into(imageView);

                } else {

                }

//                动态添加RadioButton
                for (int i = 0; i < urls.size(); i++) {
                    if (TextUtils.isEmpty(urls.get(i).getFile_link())) {
                        continue;
                    }
                    RadioButton tempButton = new RadioButton(getContext());
                    tempButton.setPadding(50, 0, 0, 0);                 // 设置文字距离按钮四周的距离
                    tempButton.setText(urls.get(i).getFile_bitrate() + "k,   " + urls.get(i).getFile_extension() + ",   "
                                               + urls.get(i).getFile_size() / 1000 + "KB");

                    tempButton.setId(i);

                    tempButton.setChecked(true);

                    radioGroup.addView(tempButton, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

                }


/*
//                隐藏不存在的音质对应按钮，并选择最高音质

                for (int i = 0; i < urls.size(); i++) {
                    switch (urls.get(i).getFile_bitrate()) {

                    }

                }

                */
/*                for (int i = 0; i < 6; i++) {
                    if (TextUtils.isEmpty(urls.get(i).getFile_link())) {
                        buttons[i].setVisibility(View.GONE);
                    }
                    if (buttons[i].getVisibility() == View.VISIBLE) {
                        buttons[i].setChecked(true);
                    }
                }*/
            }


        }
                , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        requestQueue.add(stringRequest);


        return new AlertDialog.Builder(getActivity())
                .setTitle("下载歌曲")
                .setView(view)
//                确认按钮
                .setPositiveButton("下载", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO: 2016/3/13 下载
                        Log.e("wocao", "onClick: " + radioGroup.getCheckedRadioButtonId());

//                        删除旧文件与数据库下载记录
                        if (dataBean != null) {
                            DownloadManager dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
                            dm.remove(dataBean.getDownloadId());
                            HistoryFragment_.historyAdapter.notifyDataSetChanged();

                            myDao.deleteDateBySongID(songId);
                        }
                        FileDownloader.download(getContext(), radioGroup.getCheckedRadioButtonId(), bean);
                    }
                })
//                取消按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create();
    }


}
